import pyecharts.options as opts
from pyecharts.charts import Scatter
from PyQt5.QtCore import QUrl
from PyQt5.QtWidgets import QApplication, QWidget, QHBoxLayout, QFrame
from PyQt5.QtWebEngineWidgets import QWebEngineView
import sys
import numpy as np


class Stacked(QWidget):
    def __init__(self):
        super(Stacked, self).__init__()
        self.initData()
        self.initUI()
        self.mainLayout()

    def initUI(self):
        self.setGeometry(400, 400, 800, 600)
        self.setWindowTitle(" ")

    def initData(self):
        nums = 200
        data = np.random.random((nums, 2))
        data = np.sort(data)
        x_data = data[:, 0]
        y_data = data[:, 1]

        (
            Scatter(init_opts=opts.InitOpts(width="1600px", height="1000px"))
            .add_xaxis(xaxis_data=x_data)
            .add_yaxis(
                series_name="",
                y_axis=y_data,
                symbol_size=20,
                label_opts=opts.LabelOpts(is_show=False),
            )
            .set_series_opts()
            .set_global_opts(
                xaxis_opts=opts.AxisOpts(
                    type_="value", splitline_opts=opts.SplitLineOpts(is_show=True)
                ),
                yaxis_opts=opts.AxisOpts(
                    type_="value",
                    axistick_opts=opts.AxisTickOpts(is_show=True),
                    splitline_opts=opts.SplitLineOpts(is_show=True),
                ),
                tooltip_opts=opts.TooltipOpts(is_show=False),
                toolbox_opts=opts.ToolboxOpts(
                    is_show=True,
                    orient="horizontal",
                    feature=opts.ToolBoxFeatureOpts(
                        save_as_image=opts.ToolBoxFeatureSaveAsImageOpts(type_="jpeg", title="保存为jpeg",
                                                                         pixel_ratio=2),
                        restore=opts.ToolBoxFeatureRestoreOpts(),
                        data_zoom=opts.ToolBoxFeatureDataZoomOpts(
                            xaxis_index=[0],
                            yaxis_index=[0]
                        ),
                    )
                )
            )
            .render("/tmp/scatter.html")
        )

    def mainLayout(self):
        self.mainhboxLayout = QHBoxLayout(self)
        self.frame = QFrame(self)
        self.mainhboxLayout.addWidget(self.frame)
        self.hboxLayout = QHBoxLayout(self.frame)
        self.myHtml = QWebEngineView()
        # 打开本地html文件
        self.myHtml.load(QUrl("file:////tmp/scatter.html"))
        self.hboxLayout.addWidget(self.myHtml)
        self.setLayout(self.mainhboxLayout)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Stacked()
    ex.show()
    sys.exit(app.exec_())
